#!/usr/bin/env python
# coding = utf-8

import configparser
import os
import sys
import boto3
import json
import time
import datetime
import logging
import pandas as pd
import argparse
import psutil
import xlsxwriter





conf = configparser.ConfigParser()


def readConf(section, key):
    '''读取配置文件'''
    root_path = os.path.dirname(os.path.realpath(__file__))
    conf.read(root_path + '/config/config.ini')  # 文件路径
    value = conf.get(section, key)
    return value


def get_time_interval(number, tz):
    today_date = datetime.date.today()
    interval_date = today_date - datetime.timedelta(days=number)
    date_str = interval_date.strftime("%Y-%m-%d") + ' 16:00:00'
    date_Array = time.strptime(date_str, "%Y-%m-%d %H:%M:%S")
    # date_time = time.strftime("%Y-%m-%d %H:%M:%S", date_Array)
    utcdatetime = datetime.datetime.strptime(time.strftime("%Y-%m-%d %H:%M:%S", date_Array), "%Y-%m-%d %H:%M:%S")
    localdatetime = utcdatetime + datetime.timedelta(hours=8)
    if tz == "utc":
        date_time = utcdatetime
    else:
        date_time = localdatetime

    # print (localdatetime)
    # print (type(localdatetime))
    return date_time


class DateEncoder(json.JSONEncoder):
    def default(self, obj):
        if isinstance(obj, datetime.datetime):
            return obj.strftime("%Y-%m-%d %H:%M:%S")
        else:
            return json.JSONEncoder.default(self, obj)


def token():
    client = s_session.client('sts')
    try:
        sessiontoken = client.get_session_token(
            SerialNumber=readConf(section, "SerialNumber"),
            TokenCode=sys.argv[2]
        )
    except:
        print("Invalid MFA Code")
        exit()
    accesskeyid = sessiontoken.get('Credentials').get('AccessKeyId')
    secretaccesskey = sessiontoken.get('Credentials').get('SecretAccessKey')
    sessiontoken = sessiontoken.get('Credentials').get('SessionToken')
    stssession = boto3.Session(
        aws_access_key_id=accesskeyid,
        aws_secret_access_key=secretaccesskey,
        aws_session_token=sessiontoken,
        region_name=readConf(section, "region")
    )
    return stssession


def session():
    if section == 'global' or section == 'prd':
        session = token()
    else:
        session = s_session
    return session



def cost_explorer():
    endday = datetime.date.today().replace(day=1)
    today = datetime.date.today()
    #yesterday = today - datetime.timedelta(days=1)
    client = session.client('ce')
    response = client.get_cost_and_usage(
            TimePeriod={
                'Start' : str(endday),
                'End' : str(today)
                },
            Granularity='DAILY',
            Metrics=[
                'UnblendedCost'
                ]

            )
    cost = response['ResultsByTime']
#    dict_cost = {'day': today, 'cost': cost}
#    return cost


#def excel_cost():
    workbook = xlsxwriter.Workbook('cost.xlsx')
    worksheet = workbook.add_worksheet()
#    text = cost_explorer()
#    text = cost_explorer[0],cost_explorer[1]
    title = [u'日期', u'费用']
    format_title = workbook.add_format()
    format_title.set_border(1)
    format_title.set_bg_color('#cccccc')

    format_text = workbook.add_format()
    format_text.set_border(1)

    worksheet.set_column('A:K',20)   ##设置A到K列宽度20像素
    worksheet.write_row('A1',title,format_title)   ##将title列表有A1开始横向写入，并且格式为format_title
    length_cost = len(cost)
    count = 2
    for i in range(length_cost):
        starttime = cost[i]['TimePeriod']['Start']
        expenses = float(cost[i]['Total']['UnblendedCost']['Amount'])
        data = [starttime, "%.2f" % expenses]
        print(data)
        worksheet.write_row('A'+str(i+count),data,format_text)
    workbook.close()





if __name__ == '__main__':
    try:
        section = sys.argv[1]
    except:
        print("Please provide environment configuration parameters: prd , stg , global")
        exit()
    s_session = boto3.session.Session(aws_access_key_id=readConf(section, "aws_access_key_id"),
                                      aws_secret_access_key=readConf(section, "aws_secret_access_key"),
                                      region_name=readConf(section, "region"))
    session = session()

    print(str(" SMP daily business briefing ").center(150, "="))
    if sys.argv[1] == 'prd':
        LoadBalancerValue = "app/smp-cnprd-elb-dc/d1664af97a422f0f"
        TargetGroupValue = "targetgroup/smp-cnprd-lb-tg-dc/390ee9a1fa706b93"
#        dc_pv_count(LoadBalancerValue, TargetGroupValue)
    elif sys.argv[1] == 'stg':
        LoadBalancerValue = "app/smp-cnstg-elb-dc/49873290485cddc6"
        TargetGroupValue = "targetgroup/smp-cnstg-lb-tg-dc/e4afbb2d7cd02968"
#        dc_pv_count(LoadBalancerValue, TargetGroupValue)
    else:
        print("global PV don't need Statistics")

    cost_explorer()
#    excel_cost()
